package com.alt.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.manager.ALTPTCMgr.ALERT_OPTION;
import com.alt.manager.ALTPTCMgr.COMMAND_TYPE;
import com.alt.manager.ALTPTCMgr.CONFIRM_DIALOG_ID;
import com.alt.manager.ALTPTCMgr.RECEIVER_TYPE;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.shared.DialogCommand;
import com.alt.shared.IActivityHandler;
import com.alt.shared.IServiceCommandResult;
import com.alt.shared.onImageSet;
import com.alt.utils.ALTSysUtils;
import com.alt.utils.ALTUserAlert;
import com.alt.utils.ALTUserToast;
import com.alt.R;

public class ALTBaseActivity extends Activity implements IServiceCommandResult, IActivityHandler, onImageSet {

	public ALTAppMgr m_AppMgr = null;
	public SCREEN_UI m_ThisScreenMode = null;

	// Progress dialog
	final public int PROGRESS_DIALOG = 0;

	AlertDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Set current activity
		m_AppMgr = ALTAppMgr.getInstance(this); // important!!
	}

	@Override
	protected void onResume() {
		ALTAppMgr.getInstance().Log("ALTBaseActivity", "onResume:started:" + getClass().getSimpleName());

		super.onResume();

		if (!m_AppMgr.m_Activity.equals(this)) {
			m_AppMgr = ALTAppMgr.getInstance(this);
			onSetScreenMode(m_ThisScreenMode);
		}
	}

	@Override
	public void onBackPressed() {
		ALTAppMgr.getInstance().Log("Base_onBackPressed", "BaseActivity back");

		switch (m_AppMgr.m_CurScreenMode) {
		case LOGIN:
		case HOME:
		case Personal:
			Log.v("HAI", "cart");
		case Exchange:
		case Setting:
		case MORE_UI:
			if (ALTAppMgr.isBack) {
				ALTAppMgr.isBack = false;
			} else {
				alertAppExit();
			}

			break;
		default:

			super.onBackPressed();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// do something on back.

			this.onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (m_hViewEvent != null)
			m_hViewEvent = null;

		if (m_hRecvDataEvent != null)
			m_hRecvDataEvent = null;

		switch (m_AppMgr.m_CurScreenMode) {
		case LOGIN:
			ALTAppMgr.getInstance().Log("ALTBaseActivity", "onDestroy");

			// ALTAppMgr.getInstance().setForegroundNFC(this, false);
			break;

		default:
			break;
		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case (PROGRESS_DIALOG):
			progressDialog = ALTSysUtils.createProgressDialog(this);
			return progressDialog;
		}
		return null;
	}

	// Get top parent
	public static Activity getContext(Activity current) {
		if (current.getParent() != null) {
			current = current.getParent();
			return getContext(current);
		}
		return current;
	}

	// Get TabActivity
	public static ALTMainForm getParentTab(Activity current) {
		if (current.getParent() != null) {
			current = current.getParent();

			if (current instanceof ALTMainForm) {
				return (ALTMainForm) current;
			}

			return getParentTab(current);
		}

		return null;
	}

	public void processCommandResult(int commandCode, Object resultData) {
	}

	protected void processCommandError(Bundle errorData) {
		Toast t = Toast.makeText(getApplicationContext(), errorData.getString(Intent.EXTRA_TEXT), Toast.LENGTH_LONG);
		t.show();
	}

	public void alertAppExit() {
		final Context context = this.getParent() == null ? this : this.getParent();
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(R.string.txt_app_exit);
		alert.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		alert.setMessage(R.string.msg_app_exit);
		alert.setPositiveButton(R.string.txt_btn_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				onEventReceiver(SCREEN_UI.APP_EXIT); // APP exit
				// close APP
				new ALTAppMgr().cleanCacheLocal(context);
				System.gc();
				System.exit(0);
			}
		});
		alert.setNegativeButton(R.string.txt_btn_cancel, null);
		alert.show();
	}

	public void alert(String msg) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this.getParent() == null ? this : this.getParent());
		alert.setMessage(msg);
		alert.setPositiveButton(R.string.txt_btn_ok, null);
		alert.show();
	}

	public void alert(int msgId) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this.getParent() == null ? this : this.getParent());
		alert.setMessage(msgId);
		alert.setPositiveButton(R.string.txt_btn_ok, null);
		alert.show();
	}

	//
	// =================================================================
	// Screen switching
	// =================================================================
	//
	public void onSetScreenMode(SCREEN_UI screenMode) {
		m_ThisScreenMode = screenMode;
		m_AppMgr.setScreenMode(m_ThisScreenMode);
	}

	public void onNotification(String tickerText, String contentTitle, String contentText) {
		// Get Notification Service
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		PendingIntent intent = PendingIntent.getActivity(ALTBaseActivity.this, 0, new Intent(), 0);

		// Create Notification Object
		Notification notification = new Notification(android.R.drawable.ic_input_add, tickerText, System.currentTimeMillis());

		notification.setLatestEventInfo(ALTBaseActivity.this, contentTitle, contentText, intent);
		nm.notify(1004, notification);
		// onSoundPlay(InnoSoundMgr.SOUND_AUTOORDER_FAIL);
		nm.cancel(1004);
	}

	/**
	 * 
	 * @param nextScreenMode
	 */
	public void onEventReceiver(SCREEN_UI nextScreenMode) {
		onEventReceiver(nextScreenMode, null);
	}

	/**
	 * 
	 * @param nextScreenMode
	 * @param extras
	 */
	public void onEventReceiver(SCREEN_UI nextScreenMode, Bundle extras) {
		showDialog(PROGRESS_DIALOG);

		Log.d("ALTBaseActivity::onEventReceiver", "CurScreenMode: [" + m_AppMgr.m_CurScreenMode + "], NextScreenMode: [" + nextScreenMode + "]");

		if (nextScreenMode == m_AppMgr.m_CurScreenMode) {
			dismissDialog(PROGRESS_DIALOG);
			return;
		}

		if (nextScreenMode == SCREEN_UI.APP_EXIT) {
			m_AppMgr.destroyApp();
			return;
		}

		// Activity Change
		Intent i = new Intent(ALTPTCMgr.NAME_BASE_RECEIVER);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_TYPE, RECEIVER_TYPE.UI_RECEIVER);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_NEXT_SCREEN, nextScreenMode);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_EXTRAS, extras);
		// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.setFlags(0);
		sendBroadcast(i);
	}

	public void onEventReceiver(COMMAND_TYPE commandType, Bundle extras) {
		// Activity Change
		Intent i = new Intent(ALTPTCMgr.NAME_BASE_RECEIVER);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_TYPE, RECEIVER_TYPE.CMD_RECEIVER);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_NEXT_CMD, commandType);
		i.putExtra(ALTPTCMgr.TAG_RECEIVER_EXTRAS, extras);
		// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.setFlags(0);

		sendBroadcast(i);
	}

	// View Event
	public Handler m_hViewEvent = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case ALTPTCMgr.VIEW_EVENT_TOAST:
				ALTUserToast.showToast(m_AppMgr.m_Activity, msg.obj.toString());
				break;

			case ALTPTCMgr.VIEW_EVENT_LOGIN_FAIL: {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						onEventReceiver(SCREEN_UI.APP_EXIT);
						finish();
					}
				};

				String[] msgObj = (String[]) msg.obj;
				ALTUserAlert.showAlert(m_AppMgr.m_Activity.getParent(), msgObj[0], msgObj[1], listener);
			}
				break;
			case ALTPTCMgr.VIEW_EVENT_LOGIN_SUCCEED: {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						onEventReceiver(SCREEN_UI.HOME);
						finish();
					}
				};

				// Show msg when login ok
				String[] msgObj = (String[]) msg.obj;
				ALTUserAlert.showAlert(m_AppMgr.m_Activity.getParent(), msgObj[0], msgObj[1], listener);
			}
				break;

			case ALTPTCMgr.VIEW_EVENT_EXIT_APP: {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						onEventReceiver(SCREEN_UI.APP_EXIT);
						finish();
					}
				};

				String[] msgObj = (String[]) msg.obj;
				ALTUserAlert.showAlert(m_AppMgr.m_Activity.getParent(), msgObj[0], msgObj[1], listener);
			}
				break;

			case ALTPTCMgr.VIEW_EVENT_ALERT: {
				ALERT_OPTION option = ALERT_OPTION.values()[msg.arg1];
				String title = "";

				if (option == ALERT_OPTION.ALERT_INFO) {
					title = getString(R.string.txt_label_info);
				} else if (option == ALERT_OPTION.ALERT_WARNING) {
					title = getString(R.string.txt_warning);
				} else {
					title = getString(R.string.txt_error);
				}

				String alertMsg = (String) msg.obj;
				ALTUserAlert.showAlert(m_AppMgr.m_Activity.getParent(), title, alertMsg, null);
			}
				break;

			case ALTPTCMgr.VIEW_EVENT_CONFIRMATION: {
				CONFIRM_DIALOG_ID dialogId = CONFIRM_DIALOG_ID.values()[msg.arg1];

				DialogCommand okCommand = new DialogCommand() {
					public void execute(CONFIRM_DIALOG_ID dialogId, Object data) {
						onConfirmDialogResult(dialogId, data);
					}
				};

				String title = getString(R.string.txt_btn_ok);
				String alertMsg = (String) msg.obj;
				ALTUserAlert.showConfirmation(m_AppMgr.m_Activity.getParent(), title, alertMsg, okCommand, dialogId, null);

			}
				break;

			case ALTPTCMgr.VIEW_EVENT_ERROR:
				ALTPTCMgr.ERROR errorCode = (ALTPTCMgr.ERROR) msg.obj;

				String errorTitle = getString(R.string.txt_error);
				String errorMsg = errorCode.toString();

				if (errorCode == ALTPTCMgr.ERROR.SVC_CONNECT_FAILED) {
					errorMsg = getString(R.string.msg_server_connection_failed);
				}

				ALTUserAlert.showAlert(m_AppMgr.m_Activity.getParent(), errorTitle, errorMsg, null);
				break;
			}
		}
	};

	public void onConfirmDialogResult(CONFIRM_DIALOG_ID dialogId, Object data) {
		switch (dialogId) {
		case SHOW_CART:
			onEventReceiver(SCREEN_UI.Personal);
			break;
		default:
			break;
		}
	}

	// Receive Event
	public Handler m_hRecvDataEvent = new Handler() {
		public void handleMessage(Message msg) {
			processCommandResult(msg.what, msg.obj);
		}
	};

	// end---------------------------------------

	public void CloseKeyboard(EditText id) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(id.getWindowToken(), 0);
	}

	public void hideProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}

	public void onScreenChanged(SCREEN_UI curScreen) {
		// TODO Auto-generated method stub
		hideProgressDialog();
	}

	/**
	 * Get bundle data sent from previous UI
	 * 
	 * @return
	 */
	public Bundle getScreenEventExtras() {
		Intent i = getIntent();
		return i.getBundleExtra(ALTPTCMgr.TAG_RECEIVER_EXTRAS);
	}

	public void setimage(Uri selectedImageUri, String path) {

	}


}
